package db

import (
	"context"
	"encoding/json"

	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

type Article struct {
	gorm.Model

	CategoryID uint   `gorm:"not null;index:category_id"`
	UserID     uint   `gorm:"not null"`
	Title      string `gorm:"not null"`
	Content    string `gorm:"not null"`
	Type       int8   `gorm:"not null"`
	Tags       []uint `gorm:"_"`
}

type Articles []Article

type ArticleTag struct {
	gorm.Model
	ArticleID uint `gorm:"not null;index:idx1,proiority:1;index:idx2,priority:2"`
	TagID     uint `gorm:"not null;index:idx1,proiority:2;index:idx2,priority:1"`
}

type ArticleCategory struct {
	gorm.Model
	ArticleID  uint `gorm:"not null"`
	CategoryID uint `gorm:"not null"`
}

func GetArticle(ID any) *Article {
	article := Article{}
	DB.Where("id=?", ID).First(&article)
	return &article
}

// LoadIntoRedis 函数将Articles结构体中的数据加载到Redis中
func (a Articles) LoadIntoRedis() error {
	// 遍历Articles结构体中的每个article
	for _, article := range a {
		// 将article转换为json格式
		j, err := json.Marshal(article)
		// 如果转换失败，则返回错误
		if err != nil {
			return err
		}

		// 将json格式的article添加到Redis的有序集合中
		_, err = RDB.ZAdd(context.Background(), "article:all", redis.Z{
			// 设置score为article的创建时间
			Score: float64(article.CreatedAt.Unix()),
			// 设置member为json格式的article
			Member: j,
		}).Result()
		// 如果添加失败，则返回错误
		if err != nil {
			return err
		}
	}
	// 如果所有article都添加成功，则返回nil
	return nil
}
